package com.ice.day726.thread;

import java.util.List;
import java.util.Stack;

/**
 * @Author ice2020x
 * @Date 2022-07-30 19:20
 * @Description:
 */
public class LinkedListTest {


    public static void main(String[] args) {
        Node head = new Node(0);
        Node node1 = new Node(1);
        head.next = node1;
        Node node2 = new Node(2);
        node1.next = node2;
        Node node3 = new Node(3);
        node2.next = node3;
        head.list(head);
        System.out.println("-----");
        Node node = reverseLinkedList3(head);
        head.list(node);
    }


    /**
     * @author ice2020x
     * @Date: 2022/7/30
     * @Description: 链表反转
     **/
    public static Node reverseLinkedList(Node head) {
        Node pre = null;
        Node curr = head;
        while (curr != null) {
            Node next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }


    /**
    * @author ice2020x
    * @Date: 2022/7/30
    * @Description: 基于栈的链表反转
    **/
    public static Node reverseLinkedList1(Node head) {
        Stack<Node> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }

        if (stack.isEmpty()) {
            return null;
        }

        Node node = stack.pop();
        Node temp = node;
        while (!stack.isEmpty()) {
            temp.next = stack.pop();
            temp = temp.next;
        }
        temp.next = null;
        return node;
    }


    /**
    * @author ice2020x
    * @Date: 2022/7/30
    * @Description:
    **/
    public static Node reverseLinkedList3(Node head) {
        Node node = null;
        while (head != null)
        {
            Node next = head.next;
            head.next = node;
            node = head;
            head = next;
        }
        return node;
    }
}

class Node {
    int val;
    public Node next;

    Node(int val) {
        this.val = val;
    }

    public void list(Node head) {
        Node p = head;
        while (p != null) {
            System.out.println(p.val);
            p = p.next;
        }
    }


}